import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:lite_clock/obj/chinese_calendar.dart';
import 'package:lite_clock/obj/lc_response.dart';
import 'package:lite_clock/util/app_util.dart';

///网络请求封装
class DioUtil {
  static Dio _dio = Dio();

  ///post请求
  // static const String _POST = "POST";

  ///get请求
  static const String _GET = "GET";

  ///api_key
  static String _key = 'f9081f99f4913fd8df0b0882e6d262e5';

  ///请求通道
  static Future<LcResponse> request(String api,
      {Map data, String mothed = _GET}) async {
    try {
      LC.log('请求地址:$api');
      LC.log('请求类型:[$mothed]');
      LC.log('请求参数:${json.encode(data)}');

      final Response _r = await _dio.request(
        api,
        options: Options(method: mothed),
        data: data,
      );

      LC.log("返回结果:${json.encode(_r.data)}");

      return LcResponse.fromJson(_r.data as Map);
    } catch (e) {
      throw e;
    }
  }

  ///获取农历相关信息
  static Future<ChineseCalendar> getChCalendar() async {
    try {
      final LcResponse _response = await request(
          'http://api.tianapi.com/txapi/lunar/index?key=$_key&date=${DateTime.now().millisecondsSinceEpoch ~/ 1000}');
      if (_response.code == 200) {
        final _data = _response.newslist[0];

        return ChineseCalendar.fromJson(_data as Map);
      }

      return null;
    } catch (e) {
      LC.log('获取农历相关信息出错:$e', type: 2);
      return null;
    }
  }
}
